package com.example.rabbit.demo.ack;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: rabbit-demo
 * @description:
 * @author: zhaoliang
 * @create: 2019-12-30 13:38
 */
public class Producer {

    public static void main(String[] args) throws Exception {
        //1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.200.128");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");

        //2.通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();
        //3.通过connection创建一个channel
        Channel channel = connection.createChannel();

        //4.通过channel发送数据
        String exchangeName="test_ack_exchange";
        String routingKey="ack.add";
        for(int i=1;i<=10;i++){
            String msg="Produce生产的第"+i+"条消息";
            Map<String,Object> headers = new HashMap<>();
            headers.put("num",i);
            AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                    .deliveryMode(2)//1非持久化，2代表持久化
                    .contentEncoding("UTF-8")
                    .headers(headers)
                    .build();
            channel.basicPublish(exchangeName,routingKey,true,properties,msg.getBytes());
        }
        //5.关闭相关连接
        channel.close();
        connection.close();

    }
}
